Categories
JavaScript Tips

JavaScript Tips — Calculating Time Difference, The Remainder Operator, and More

Spread the love

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Get the Time Difference Between two Date-Times and Format it in HH:mm:ss Format

To get the time difference between 2 date times, we can use the diff method from moment.js

This way, we don’t have to do the calculations ourselves,

For instance, we can write:

const earlierDateTime = "04/09/2020 14:00:00";
const laterDateTime = "04/09/2020 16:20:30";

const difference = moment(laterDateTime, "DD/MM/YYYY HH:mm:ss").diff(moment(earlierDateTime, "DD/MM/YYYY HH:mm:ss"))

const diff = moment.utc(difference).format("HH:mm:ss");

We call diff to get the difference of laterDateTime and earlierDateTime and convert the difference to UTC.

This will output the difference in HH:mm:ss format.

We get ‘02:20:30' as the value of diff .

If the difference between the 2 date-times is longer than today, then we’ve to some extra calculations.

For instance, we can write:

const earlierDateTime = "04/09/2020 14:00:00";
const laterDateTime = "14/09/2020 16:20:30";
const ms = moment(laterDateTime, "DD/MM/YYYY HH:mm:ss").diff(moment(earlierDateTime, "DD/MM/YYYY HH:mm:ss"));

const d = moment.duration(ms);

const diff = `${Math.floor(d.asHours())}${moment.utc(ms).format(":mm:ss")}`;
console.log(diff);

We calculate the minutes and seconds between the 2 dates with the diff method.

Then we call the duration method to get the duration.

Then we can use the asHours method on the duration d object to get the hours elapsed.

We use the utc method to format the minutes and seconds.

string.charAt(x) vs string[x]

The charAt and the bracket notation for getting a character from a string are the same.

They’re both supported by almost all modern browsers.

For instance:

"foo bar"[2]

is the same as:

"foo bar".charAt(2)

Check if a JavaScript Object is a DOM Object

To check if an object is a DOM object, we can write:

typeof Node === "object" ? obj instanceof Node :
  obj && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string"

We check if the Node object exists.

If it is, then we check the obj object with the instanceof operator.

Otherwise, we’ve to check if some properties exist.

We check the nodeType property and nodeName is a string.

To check for an element, we can write:

typeof HTMLElement === "object" ? obj instanceof HTMLElement :
  typeof obj === "object" && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === "string"

We check if the HTMLElement object exists in the browser.

If it does, we just use the instanceof operator.

Otherwise, we check if obj is an object, and also check the nodeType and nodeName properties.

nodeType 1 means that the node is an HTML element.

Get the Length of a String

We can use the length property of a string to get its length.

For instance, we can write:

const str = 'foo';
const length = str.length;

Get the Decimal Portion of a Number

To get the decimal portion of a number, we can use the % operator.

We get the remainder of the number divided by 1.

For instance, we can write:

2.555 % 1

Then we get:

0.5550000000000002

returned.

We can also convert it to a string and call split on it:

(2.555).toString().split(".");

The decimal part would be in index 1 of the returned array.

Run a Function When the Page is Loaded

We can function a function when a page is loaded by setting the function as a value of the window.onload property.

For instance, we can write:

window.onload = () => {
  console.log('page loaded');
}

We set the function as the value of onload so it’ll run when the page loads.

Determine if a Number is Odd

We can determine if a number is odd by using the remainder operator.

For example, we can write:

x % 2 !== 0

If x can’t be evenly divided by 2, then we know it’s odd.

Conclusion

We can format a time span into HH:mm:ss format with moment.js.

We can use the % operator to determine if a number is odd.

Most of the time, we can use the built-in constructors to check if an object is a DOM node or element.

Getting the decimal portion of a number can be done by getting the remainder when divided by 1 or convert it to a string and split it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *